//
//  GYLockAutoAlertView.m
//  LockManagement
//
//  Created by 丁燕春 on 2018/8/19.
//  Copyright © 2018年 yunjiazhineng. All rights reserved.
//

#import "GYLockAutoAlertView.h"
#import "GYNetWorkTools.h"
#import "GYKey.h"
#import "DateTimePickerView.h"
#import "GYDateTools.h"

@interface GYLockAutoAlertView()<UITableViewDelegate,UITableViewDataSource,DateTimePickerViewDelegate>

@property (weak, nonatomic) IBOutlet UILabel *autoTypeLable;
@property (weak, nonatomic) IBOutlet UILabel *beginTimeLbale;
@property (weak, nonatomic) IBOutlet UILabel *endTimeLable;
@property (weak, nonatomic) IBOutlet UILabel *keyNameLable;
@property (weak, nonatomic) IBOutlet UITextField *taskNameTF;
@property (weak, nonatomic) IBOutlet UIButton *confirmBtn;
@property (weak, nonatomic) IBOutlet UIButton *cancelBtn;
@property (weak, nonatomic) IBOutlet UIView *authoAlertView;

/** 选择钥匙列表 */
@property (nonatomic, strong) GYKey *key;

/** 选择表格 */
@property (nonatomic, strong) UITableView *chooseTableView;

/**任务类型选择类型 */
@property (nonatomic, strong) NSArray *typeLists;

/** 钥匙选择列表 */
@property (nonatomic, strong) NSArray *keyList;

//代表加载哪个列表
@property (nonatomic, getter=isType) BOOL type;

//代表选择开始或则结束时间
@property (nonatomic, getter=isBegin) BOOL begin;

/**
 时间选择器
 */
@property (strong, nonatomic) DateTimePickerView *datePickerView;

@end


@implementation GYLockAutoAlertView

+ (instancetype)initWithFrame:(CGRect)frame {
    GYLockAutoAlertView *lockAlertView = [[[NSBundle mainBundle] loadNibNamed:NSStringFromClass(self) owner:nil options:nil] firstObject];
    lockAlertView.frame = frame;
    
    return lockAlertView;
}

- (void)awakeFromNib {
    [super awakeFromNib];
    self.backgroundColor = [UIColor colorWithWhite:0.8 alpha:0.5];
    
    //给lable添加点击手势
    [self addTap:self.autoTypeLable action:@selector(chooseType:)];
    [self addTap:self.beginTimeLbale action:@selector(chooseTime:)];
    [self addTap:self.endTimeLable action:@selector(chooseTime:)];
    [self addTap:self.keyNameLable action:@selector(chooseKey:)];

    //设置控件属性
    [self setViewAttributes:self.authoAlertView];
    [self setViewAttributes:self.autoTypeLable];
    [self setViewAttributes:self.beginTimeLbale];
    [self setViewAttributes:self.endTimeLable];
    [self setViewAttributes:self.keyNameLable];
    [self setViewAttributes:self.confirmBtn];
    [self setViewAttributes:self.cancelBtn];
    
}

- (IBAction)registerFirstRespond:(UITextField *)sender {
    [sender resignFirstResponder];
}


#pragma mark -- 点击手势方法

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    NSSet *allTouches = [event allTouches];    //返回与当前接收者有关的所有的触摸对象
    UITouch *touch = [allTouches anyObject];   //视图中的所有对象
    CGPoint currentPoin = [touch locationInView:self]; //返回触摸点在视图中的当前坐标
    if (!CGRectContainsPoint(self.authoAlertView.frame, currentPoin)) {
        [self removeFromSuperview];
    }else {
        [self endEditing:YES];
    }
}


/**
选择类型

 @param tap <#tap description#>
 */
- (void)chooseType:(UITapGestureRecognizer *)tap {
    self.type = YES;
    //1.设置表格的表格的frame
    [UIView animateWithDuration:0.5 animations:^{
        self.chooseTableView.frame = CGRectMake(10, self.beginTimeLbale.y-10, self.autoTypeLable.width, self.typeLists.count > 3 ? 150 : (self.typeLists.count*50));
        [self.authoAlertView addSubview:self.chooseTableView];
        [self.chooseTableView reloadData];
    }];
}

/**
 选择任务时间

 @param tap <#tap description#>
 */
- (void)chooseTime:(UITapGestureRecognizer *)tap {
    if (tap.view == self.beginTimeLbale) {
        self.begin = YES;
    }else {
        self.begin = NO;
    }
    DateTimePickerView *pickerView = [[DateTimePickerView alloc] init];
    self.datePickerView = pickerView;
    pickerView.delegate = self;
    pickerView.pickerViewMode = DatePickerViewDateTimeMode;
    [self addSubview:pickerView];
    [pickerView showDateTimePickerView];
}

/**
 选择任务钥匙

 @param tap <#tap description#>
 */
- (void)chooseKey:(UITapGestureRecognizer *)tap {
    self.type = NO;
    //1.设置表格的表格的frame
    if (self.keyList.count == 0) {
        [SVProgressHUD showInfoWithStatus:@"没有可选择的钥匙!"];
        [SVProgressHUD dismissWithDelay:0.8];
        
        return;
    }
    
    [UIView animateWithDuration:0.5 animations:^{
        self.chooseTableView.frame = CGRectMake(10, self.taskNameTF.y-20, self.keyNameLable.width, self.keyList.count > 3 ? 150 : (self.keyList.count*50));
        [self.authoAlertView addSubview:self.chooseTableView];
        [self.chooseTableView reloadData];
    }];
}

- (void)addTap:(id)sender action:(SEL)action{
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:action];
    [sender addGestureRecognizer:tap];
}

#pragma mark - delegate

- (void)didClickFinishDateTimePickerView:(NSString *)date{
    if (self.isBegin) {
        self.beginTimeLbale.text = date;
    }else {
        //要判断后面选择的时间是不是比前面这个时间打
        NSString *style = @"yyyy-MM-dd HH:mm";
        NSDate *beginDate = [GYDateTools date:self.beginTimeLbale.text WithDateFormat:style];
        NSDate *endDate = [GYDateTools date:date WithDateFormat:style];
        NSComparisonResult result = [endDate compare:beginDate];
        if (result == NSOrderedDescending) {
            self.endTimeLable.text = date;
        }else {
            [SVProgressHUD showInfoWithStatus:@"请选择一个大于开始时间的时间!"];
        }
    }
}

#pragma mark --- 按钮点击事件
- (IBAction)onClick:(UIButton *)sender {
    if (sender.tag == 1) {
        
        if ([self.beginTimeLbale.text isEqualToString:@"开始时间"]) {
            [SVProgressHUD showInfoWithStatus:@"请选择开始时间!"];
            
            return;
        }
        
        if ([self.endTimeLable.text isEqualToString:@"结束时间"]) {
            [SVProgressHUD showInfoWithStatus:@"请选择结束时间!"];
            
            return;
        }
        
        if ([self.keyNameLable.text isEqualToString:@"请选择钥匙"]) {
            [SVProgressHUD showInfoWithStatus:@"请选择钥匙!"];
            return;
        }
        
        NSString *type;
        if ([self.autoTypeLable.text isEqualToString:@"开锁"]) {
            type = @"2";
        }else if ([self.autoTypeLable.text isEqualToString:@"巡更"]) {
            type = @"0";
        }else if ([self.autoTypeLable.text isEqualToString:@"关锁"]) {
            type = @"3";
        }
        NSString *style = @"yyyy-MM-dd HH:mm";
        NSString *IP = GETOBJ(@"IP")
        NSString *port = GETOBJ(@"port")
        NSLog(@"发送一个确认申请的网络请求,然后删除视图");
        NSString *taskStart = [GYDateTools dateString:self.beginTimeLbale.text withDateFormatter:style];
        NSString *taskEnd = [GYDateTools dateString:self.endTimeLable.text withDateFormatter:style];
        
        [GYNetWorkTools requestTaskApplyWithURL:[NSString stringWithFormat:@"http://%@:%@/api/taskApply",IP,port] keyID:[NSString stringWithFormat:@"%d",self.key.keyID] lockID:self.lockID taskName:self.taskNameTF.text taskStart:taskStart taskEnd:taskEnd taskType:type Withsuccess:^(NSDictionary *obj) {
            //NSLog(@"obj======%@",[obj objectForKey:@"msg"]);
            [self removeFromSuperview];
            int state = [[obj objectForKey:@"state"] intValue];
            if (state == 0) {
                NSLog(@"申请  成功.....");
                [SVProgressHUD showSuccessWithStatus:@"申请任务成功!"];
            }else {

                [SVProgressHUD showErrorWithStatus:@"申请失败,请重新申请!"];
            }

        } error:^(NSError *error) {
            [self removeFromSuperview];
            [SVProgressHUD showErrorWithStatus:@"您的网络可能不太通畅..."];
            NSLog(@"task apple error ====  %@",error);
        }];
    }else {
        [self removeFromSuperview];
    }
}

- (void)setViewAttributes:(UIView *)sender {
    sender.layer.cornerRadius = 4;
    sender.layer.masksToBounds = YES;
}

#pragma mark  UITableViewDelegate,UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.isType ? self.typeLists.count : self.keyList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *cellIdentifier = @"cellIdentifier";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    if (self.isType) {
        cell.textLabel.text = self.typeLists[indexPath.row];
    }else {
        cell.textLabel.text = [self.keyList[indexPath.row] keyName];
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (self.isType) {
        self.autoTypeLable.text = self.typeLists[indexPath.row];
    }else {
        GYKey *key = self.keyList[indexPath.row];
        self.key = key;
        self.keyNameLable.text = key.keyName;
        
        
    }
    [self.chooseTableView removeFromSuperview];
}


#pragma mark -- 懒加载

- (UITableView *)chooseTableView {
    if (!_chooseTableView) {
        _chooseTableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _chooseTableView.delegate = self;
        _chooseTableView.dataSource = self;
        _chooseTableView.rowHeight = 50;
    }
    
    return _chooseTableView;
}

- (NSArray *)typeLists {
    if (!_typeLists) {
        _typeLists =@[@"巡更",@"开锁",@"关锁"];
    }
    
    return _typeLists;
}

- (NSArray *)keyList {
    if (!_keyList) {
        NSString *filePath = [NSString CachesDir:@"keys.plist"];
        NSArray *temp = [NSArray arrayWithContentsOfFile:filePath];
        NSMutableArray *models = [NSMutableArray array];
        for (NSData *data in temp) {
            GYKey *key = [NSKeyedUnarchiver unarchiveObjectWithData:data];
            [models addObject:key];
        }
        if (models.count == 0) {
            _keyList = [NSArray array];
        }
        _keyList = models;
    }
    
    return _keyList;
}






@end
